let contractId;
let productOrderId;
let returnMoneyId,productName,finishOrderProductNum;//回款id,产品名称,产品号
let currentIframe = $(getIframeByElement(document.body));
let currentRoute = currentIframe.attr("src");
let baseInfo = getParamsObj(currentRoute);
let flowId = baseInfo.flowId?baseInfo.flowId:'';
let returnMoneyBtn='';//点击打开的回款按钮对象
let payNumber,customerPayId,payMoney,customerId,payType,relateType;
$(function () {
    relationFormValidator();
    relationPayFormValidator();
    assignment()
})
function assignment(){
    $.ajax({
        url: '/bankFlow/queryInfo',
        type: 'GET',
        dataType: 'json',
        data: {
            flowId:flowId
        },
        success:(function(data) {
            if(data.code == '000000') {
                baseInfo=data.data;

                //基本信息赋值 赋值节点的id和数据中的key一致
                let demos=$(".contractTypeContainer>.form-group");
                for(let i=0;i<demos.length;i++){
                    if(demos.eq(i).find("span").length==1){
                        var id=demos.eq(i).find("span").attr('id');
                        demos.eq(i).find("span").text(baseInfo[id]);
                    }else{
                        var id=demos.eq(i).find("textarea").attr('id');
                        demos.eq(i).find("textarea").text(baseInfo[id]);
                    }
                }
                if(baseInfo['currentTrueCompanyName']){
                    $("#branchAccount").show();
                    $("#branchAccount").text(baseInfo['currentTrueCompanyName'])
                }else{
                    $("#branchAccount").hide()
                }
            }
        }),
        error:(function() {
            $.alert('请求错误');
        })
    })

}

//将路由上的参数转为对象的形式
function getParamsObj(currentRoute){
    if(currentRoute.indexOf("?")){
        let paramsStr=currentRoute.substring(currentRoute.indexOf("?")+1);
        let paramsArr=paramsStr.split('&');
        let obj={};
        for(var i=0;i<paramsArr.length;i++){
            var paramItem=paramsArr[i];
            var key=paramItem.split('=')[0];
            var value=paramItem.split('=')[1]=='null'?'':paramItem.split('=')[1];
            obj[key]=value;
        }
        return obj

    }else{
        return {};
    }
}

let format = {
    genderOpt:function(value, row, index) {
        if(row.payStatus==1){
            return '<button type="button" class="btn btn-default" id="detailBtn">查看</button>'
        }else if(row.payStatus==0){
            return '<button type="button" class="btn btn-default" id="relateBtn">关联</button>'
        }

    },
    activeOperate:function (value, row) {
        let operatorTypeName;
        switch(row.operatorTypeName){
            case '1':
                operatorTypeName='修改';
                break;
            case '2':
                operatorTypeName='删除';
                break;
            case '3':
                operatorTypeName='退款';
                break;
            case '4':
                operatorTypeName='关联';
                break;

        }
        return  operatorTypeName;
    },
};
window.operateEvents = {
    'click #relateBtn': function (e, value, row, index){
        payNumber=row.payNumber;
        customerPayId=row.customerPayId;
        payMoney=row.payMoney;
        customerId=row.customerId;
        payType=row.payType;
        openReturnMoneyModal('payNumber')
    },
    'click #detailBtn': function (e, value, row, index){
        getExchangeDetail(row.customerPayId);
        $("#exchangeDetailModal").modal('show');
    }
}
let fileObj={
    "paymentAccount":"付款账号",
    "paymentUnit": "付款单位",
    "payNumber": "充值码",
    "paymentDate": "到款时间",
    "payMoney": "到款金额",
    "arriveUnitName": "到款单位名称",
    "createPeopleName": "录入人",
    "createTm": "创建时间",
    "remark":'备注'
};
function getExchangeDetail(customerPayId){
    $.ajax({
        url: '/customerPay/queryCustomerPayDetail?customerPayId='+customerPayId,
        type: 'GET',
        success: (function (data) {
            if (data.code == '000000') {
                getHtml('exchangeDtails',data.data,fileObj)
            }
        }),
        error: (function () {
            $.alert("请求失败");
        })
    })

}
function getHtml(parentId,dataObj,fileObj){
    let html='';
    var str1='';
    for(var key in fileObj){
        var label=fileObj[key],
        value=(!dataObj[key] && typeof(dataObj[key])!="undefined" && dataObj[key]!=0)?'':dataObj[key];
        if(key=='remark'){
            str1=`<textarea class="form-control" readonly id="remarks" rows="3" style="width:calc(100% + 25px);resize:none">${value}</textarea>`
        }else{
            str1=`<span style="line-height: 35px;font-weight:bold;margin-left:5px;">${value}</span>`;
        }
        var str0=key=='remark'?`col-lg-12 col-md-12 col-sm-12`:`col-lg-6 col-md-6 col-sm-6`;
        var str=`<div class="form-group clearFix`+str0+`col-xs-12">
                            <label class="control-label pull-left">${label}:</label>
                            <div class="form-content">`+str1+`                             
                            </div>
                        </div>`;
        html+=str;
    }
    $(`#${parentId}`).html(html)

}
let payNumberColumns=[{title: '主键', field: 'customerPayId', visible: false},
    {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
    {title: '客户名称',field: 'customerName', align: 'left', valign: 'middle'},
    {title: '充值金额',field: 'payMoney', align: 'left', valign: 'middle',sortable: true},
    {title: '充值码',field: 'payNumber', align: 'left', valign: 'middle'},
    {title: '充值类型', field: 'payType', align: 'left', valign: 'middle',formatter: payTypeFormat},
    {title: '充值状态', field: 'payStatus', align: 'left', valign: 'middle',formatter: payStatusFormat,sortable: true,},
    {title: '申请人', field: 'createPeopleName', align: 'left', valign: 'middle',sortable: true,},
    {title: '所属公司', field: 'companyName', align: 'left', valign: 'middle', visible: false,sortable: true,},
    {title: '申请时间', field: 'createTm', sortable: true,align: 'left', valign: 'middle'},
    {title: '到款日期', field: 'paymentDate', sortable: true,align: 'left', valign: 'middle'},
    {title: '审批人', field: 'financeName', sortable: true,align: 'left', valign: 'middle'},
    {title: '操作',field: 'operate',align: 'right',events: operateEvents,formatter: format.genderOpt}];

//修改记录
let activeColumns=[
    {
        title: '序号', align: 'left', valign: 'middle', width: '50',
        formatter: function (value, row, index) {
            return index + 1;
        }},
    {title: '回款编号', field: 'arriveNum', align: 'left', valign: 'middle'},
    {title: '动作', field: 'operatorTypeName', align: 'left', valign: 'middle',formatter: format.activeOperate},
    {title: '修改前信息', field: 'formerData', align: 'left', valign: 'middle',formatter : function(value, row, index, field){
            var values=value?value:'-';
            return `<span style='display: inline-block;overflow: hidden;text-overflow: ellipsis;max-width:inherit;white-space: nowrap;' data-toggle='tooltip' data-placement="top" data-original-title="${values}">${values}</span>`;
        },
        cellStyle : function(value, row, index, field){
            return {
                css: {
                    "white-space": "nowrap",
                    "text-overflow": "ellipsis",
                    "overflow": "hidden",
                    "max-width":"200px"
                }
            };
        }},
    {title: '修改后信息', field: 'newData', align: 'left', valign: 'middle',formatter : function(value, row, index, field){
            var values=value?value:'-';
            return `<span style='display: inline-block;overflow: hidden;text-overflow: ellipsis;max-width:inherit;white-space: nowrap;' data-toggle='tooltip' data-placement="top" data-original-title="${values}">${values}</span>`;
        },
        cellStyle : function(value, row, index, field){
            return {
                css: {
                    "white-space": "nowrap",
                    "text-overflow": "ellipsis",
                    "overflow": "hidden",
                    "max-width":"200px"
                }
            };
        }},
    {title: '修改时间', field: 'createTm', align: 'left', valign: 'middle'},
    {title: '修改人', field: 'createPeopleName', align: 'left', valign: 'middle'},
];
//回款记录
let returnColumns=[
    {title: '主键', field: 'returnMoneyId',visible: false},
    {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
    {title: '流水号', field: 'transacationNo', align: 'left', valign: 'middle'},
    {title: '产品名称', field: 'productName', align: 'left', valign: 'middle'},
    {title: '产品号', field: 'finishOrderProductNum', align: 'left', valign: 'middle'},
    {title: '付款账号', field: 'oppositeBankAccount', align: 'left', valign: 'middle'},
    {title: '付款单位', field: 'oppositeCompany', align: 'left', valign: 'middle'},
    {title: '到款时间',field: 'arriveTime', align: 'left', valign: 'middle'},
    {title: '到款金额',field: 'arriveMoney',align: 'left', valign: 'middle'},
    {title: '到款单位名称', field: 'payeeName',align: 'left', valign: 'middle'},
    {title: '录入人', field: 'createPeople',  align: 'left',valign: 'middle'},
    {title: '创建时间', field: 'createTm',  align: 'left',valign: 'middle'},
]

function tableList(domId,url,columns,queryParams) {
    $(`#${domId}`).bootstrapTable('destroy');
    $(`#${domId}`).bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: url,
        method: 'get',                                      // 请求方式
        contentType: 'application/x-www-form-urlencoded',   // 请求内容类型
        dataType: 'json',                                   // 数据类型
        striped: true,                                      // 是否显示行间隔色
        sortable: true,                                     // 是否启用排序
        sortOrder: 'desc',                                  // 排序方式
        sortName: 'createTm',                               // 排序字段
        cache: false,                                       // 是否使用缓存
        showColumns: false,                                 // 显示隐藏列
        showRefresh: false,                                 // 显示刷新按钮
        showToggle: false,                                  // 切换显示样式
        showFooter: false,                                  // 显示Table脚部
        pagination: true,                                   // 是否显示分页
        showPaginationSwitch: false,                        // 是否显示分页按钮
        clickToSelect: true,                                // 是否启用点击选中行
        maintainSelected: true,                             // 分页是否保留选中
        singleSelect: false,
        undefinedText: '-',                                 // cell没有值时显示
        sidePagination: 'server',                           // 分页方式：client客户端分页，server服务端分页
        uniqueId: 'transactionNo',
        idField: 'transactionNo',
        pageSize: 20,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [20, 50],//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber:domId=='relationTable'?1:0,    // 右侧固定列
        queryParams: queryParams,  // 查询参数
        columns: columns,
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
            $("[data-toggle='tooltip']").tooltip({
                "container": 'body',
            })
        },
        onLoadError: function (status) {
            if (status == 403) {
                $.alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                $.alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}
//回款信息初始化
function relationFile(type){
    $("#remark").val('');
    if(type=='all'){
        $("#arriveMoney").val($("#residueMoneyAmount").text().replaceAll(',',''));//到款金额
    }else if(type=='payNumber'){
        $("#arriveMoney").val(payMoney);//到款金额
    }
    $('#arriveTime').val(baseInfo.transactionDate);
    $("#arriveAccountType").val(baseInfo.payeeName);
    $("#paymentUnit").val(baseInfo.oppositeCompany);//付款单位
    $("#paymentAccount").val(baseInfo.oppositeBankAccount);//付款账号
    $("#paymentBank").val(baseInfo.oppositeBank);//付款银行
    $('#serial').val(baseInfo.transactionNo);//流水号
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}
function searchModuleShow(){
    $("#relationAll").show();
    $("#orderInfo").show();

    $("#orderDetail").show();
    $("#productDetail").show();
    $("#customerPayContainer").hide()
}
function searchPayModuleShow(){
    $("#relationAll").hide();
    $("#orderInfo").show();

    $("#customerPayContainer").show();
    $("#orderDetail").hide();
    $("#productDetail").hide();
}
// function searchModulHide(){
//     $("#relationAll").hide();
//     $("#orderInfo").hide();
// }
//订单详情
function orderDetail(data){
    if(data.orderStatus==1){
        //未回款才显示 全部关联
        $("#relationAll").show()
    }else{
        $("#relationAll").hide()
    }
    $("#payNumber").val('');
    $("#payNumberText").text('');
    payNumber='';
    customerPayId='';
    customerId='';
    payType=null;
    var bootstrapValidator = $("#relationPayForm").data('bootstrapValidator');
    if (bootstrapValidator) {
        $("#relationPayForm").data('bootstrapValidator').destroy();
        $('#relationPayForm').data('bootstrapValidator', null);
    }
    relationPayFormValidator();
    $("#orderNumberText").text(data.orderNumber?data.orderNumber:'');
    $("#createTm").text(data.createTm?data.createTm:'');
    let orderStatus='';
    if(data.orderStatus=='1'){
        orderStatus='等待回款';
    }else if(data.orderStatus=='2'){
        orderStatus='已完成';
    }else if(data.orderStatus=='3'){
        orderStatus='作废';
    }else if(data.orderStatus=='4'){
        orderStatus='部分回款';
    }else if(data.orderStatus=='5'){
        orderStatus='预回款';
    }
    if(data.preReturnMoneyTotal>0){
        $("#residueMoneyAmountTip").text('(含预回款：'+data.preReturnMoneyTotal+')')
    }else{
        $("#residueMoneyAmountTip").text('')
    }
    $("#orderStatus").text(orderStatus);
    $("#createPeopleName").text(data.createPeopleName?data.createPeopleName:'');
    $("#companyName").text(data.companyName?data.companyName:'');
    $("#customerName").text(data.customerName?data.customerName:'');
    $("#contractNumber").text(data.contractNumber?data.contractNumber:'');
    let contractType='';
    if(data.contractType=='1'){
        contractType='非会员合同';
    }else if(data.contractType=='2'){
        contractType='会员新单合同';
    }else if(data.contractType=='3'){
        contractType='活动合同';
    }else if(data.contractType=='4'){
        contractType='会员续费合同';
    }else if(data.contractType=='5'){
        contractType='兑换合同';
    }else if(data.contractType=='6'){
        contractType='单品合同';
    }else if(data.contractType=='7'){
        contractType='会员单次';
    }
    $("#contractType").text(contractType);
    let contractStartEndDate=(data.contractStartDate||data.contractEndDate)?(data.contractStartDate+'至'+data.contractEndDate):'';
    $("#contractStartEndDate").text(contractStartEndDate);
    $("#orderActualTotalAmount").text(toThousandsFormates(data.orderActualTotalAmount));
    $("#returnMoneyAmount").text(toThousandsFormates(data.returnMoneyAmount));
    $("#residueMoneyAmount").text(toThousandsFormates(data.residueMoneyAmount));
    contractId=data.contractId;


}
//产品明细
function productDetail(data){
    var html='';
    if(data.length>0){
        for(var i=0;i<data.length;i++){
            var item=data[i];
            var str='';
            var str1= item.residueMoney?`<div class="clearFix productFileContainer">
                                            <div style="display:none" class="productCode">${item.productCode?item.productCode:''}</div>
                                            <div style="display:none" class="orderDetailType">${item.orderDetailType?item.orderDetailType:''}</div>
                                            <div style="display:none" class="productCategories">${item.productCategories?item.productCategories:''}</div>
                                            <div style="display:none" class="productId">${item.productId?item.productId:''}</div>
                                            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <span class="pull-left" style="font-size:14px;font-weight:400;color:#657082;margin-right:10px">关联金额:</span>
                                                <form class="form-horizontal pull-left" style="min-width:80px;width:calc(100% - 75px)">
                                                    <div class="row form-group clearFix">
                                                        <input class="form-control partRelationMoney" onkeyup="value=value.replace(/^\\\\D*(\\\\d*(?:\\\\.\\\\d{0,4})?).*$/g, '$1')" type="text">
                                                    </div>
                                                </form>
                                            </div>
                                            <div class="col-lg-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <button class="btn btn-primary partRelationBtn" type="button" onclick="openReturnMoneyModal('part',this)">确定</button>
                                            </div>
                                        </div>`:'';
            var str2=`<div class="pull-left contentCon">
                                        <div class="clearFix productNameContainer">
                                            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <p class="productName">产品名称</p>
                                            </div>
                                        </div>
                                        <div class="clearFix productFileContainer">
                                            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <span class="productValue orderText productNameText">${item.productName}</span>
                                            </div>
                                            <div class="col-lg-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <p class="productName">(产品编号:${item.finishOrderProductNum})</p>
                                            </div>
                                        </div>
                                        <div class="clearFix productFileContainer">
                                            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <span class="productName">产品成交价</span>
                                                <span class="productValue">${item.productFinalPrice}</span>
                                            </div>
                                            <div class="col-lg-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <span class="productName">当前回款:</span>
                                                <span class="productValue">${item.paidMoney}</span>
                                            </div>
                                            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <span class="productName">当前尾款:</span>
                                                <span class="productValue residueMoney">${item.residueMoney}</span>
                                                <span class="residueMoneyTip">${item.productPreReturnMoney>0?'(含预回款：'+item.productPreReturnMoney+')':''}</span>
                                            </div>
                                        </div>`+str1+`
                                    </div>
                                </div>
                            </div>`
            if(item.productCategories=='1'){
                //会员产品
                str=`<div class="productDetailModule memberModule">
                               <div class="finishOrderProductId" style="display:none">${item.finishOrderProductId}</div>
                               <div class="finishOrderProductNum" style="display:none">${item.finishOrderProductNum}</div>
                                <header>会员产品</header>
                                <div class="content clearFix">
                                    <div class="pull-left iconCon">
                                        <img src="../../../../images/finance/serialQuery/member.png" alt="">
                                    </div>`+str2

            }else{
                //非会员产品 附加费用
                if(item.finishOrderProductNum=='001'){
                    //附加费用
                    str=`<div class="productDetailModule additionalModule">
                                <div class="finishOrderProductId" style="display:none">${item.finishOrderProductId}</div>
                                <div class="finishOrderProductNum" style="display:none">${item.finishOrderProductNum}</div>
                                <header>附加费用</header>
                                <div class="content clearFix">
                                    <div class="pull-left iconCon">
                                        <img src="../../../../images/finance/serialQuery/fujiafeiyong.png" alt="">
                                    </div>
                                    <div class="pull-left contentCon">
                                        <div class="clearFix productFileContainer">
                                            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <span class="productName">费用金额</span>
                                                <span class="productValue">${item.orderSurcharge}</span>
                                            </div>
                                            <div class="col-lg-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <span class="productName">当前回款:</span>
                                                <span class="productValue">${item.paidMoney}</span>
                                            </div>
                                            <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 pull-left clearFix">
                                                <span class="productName">当前尾款:</span>
                                                <span class="productValue residueMoney">${item.residueMoney}</span>
                                                <span class="residueMoneyTip">${item.productPreReturnMoney>0?'(含预回款：'+item.productPreReturnMoney+')':''}</span>
                                            </div>
                                        </div>`+str1+`
                                    </div>
                                </div>
                            </div>`
                }else{
                    //非会员产品
                    str=`<div class="productDetailModule noMemberModule">
                               <div class="finishOrderProductId" style="display:none">${item.finishOrderProductId}</div>
                               <div class="finishOrderProductNum" style="display:none">${item.finishOrderProductNum}</div>
                                <header>非会员产品</header>
                                <div class="content clearFix">
                                    <div class="pull-left iconCon">
                                        <img src="../../../../images/finance/serialQuery/noMember.png" alt="">
                                    </div>`+str2
                }
            };
            html+=str;
        }
    }else{
        html=`<p>暂无产品明细</p>`
    }

    $("#productDetailContainer").html(html)
}
//客户充值
let payNumberParams=function(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort;
    params.sortOrder = params.order;
    params.payNumber = $.trim($("#payNumberText").text());
    params.flowId = flowId;
    return params
};
//回款记录
let returnParams=function(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort;
    params.sortOrder = params.order;
    params.orderNumber = $.trim($("#orderNumberText").text());
    params.payNumber = $.trim($("#payNumberText").text());
    params.flowId = flowId;
    return params
};
//修改记录
let reviseParams=function(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort;
    params.sortOrder = params.order;
    params.flowId = flowId;
    params.orderNumber = $.trim($("#orderNumberText").text());
    params.payNumber = $.trim($("#payNumberText").text());
    params.flowId = flowId;
    return params
};
/*
订单编号查询*/
function searchOrder() {
    // 验证表单
    var bootstrapValidator = $("#relationForm").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }
    $.ajax({
        url: '/bankFlow/queryByOrderNumber',
        type: 'GET',
        dataType: 'json',
        data: {
            orderNumber:$.trim($("#orderNumber").val()),
            flowId:flowId
        },
        success:(function(data) {
            if(data.code == '000000') {
                searchModuleShow();
                if(!jQuery.isEmptyObject(data.data)){
                    let orderDetailVO=data.data.orderDetailVO;
                    let contract=data.data.contract;
                    let orderDetailObj = {};
                    Object.assign(orderDetailObj ,contract,orderDetailVO);
                    if(!jQuery.isEmptyObject(orderDetailObj)){
                        orderDetail(orderDetailObj);
                    }
                    let productOrderDetailObj=data.data.productList;
                    if(!jQuery.isEmptyObject(productOrderDetailObj)){
                        productDetail(productOrderDetailObj.list);
                    }else{
                        productDetail([]);
                    }

                    productOrderId=data.data.productOrderId;
                }
                tableList('returnMoneyTable','/bankFlow/query/returnMoney',returnColumns,returnParams);

                tableList('reviseRecordTable','/bankFlow/query/operatorLog',activeColumns,reviseParams);
            }
            else if(data.code == '-1'){
                $.alert(data.data)
            }
        }),
        error:(function() {
            $.alert('查询订单出错，请重试！');
        })
    })
}
//更新订单编号查询结果
function updataResult(){
    $.ajax({
        url: '/bankFlow/queryByOrderNumber',
        type: 'GET',
        dataType: 'json',
        data: {
            orderNumber:$.trim($("#orderNumberText").text()),
            flowId:flowId
        },
        success:(function(data) {
            if(data.code == '000000') {
                if(!jQuery.isEmptyObject(data.data)){
                    let orderDetailVO=data.data.orderDetailVO;
                    let contract=data.data.contract;
                    let orderDetailObj = {};
                    Object.assign(orderDetailObj ,contract,orderDetailVO);
                    if(!jQuery.isEmptyObject(orderDetailObj)){
                        orderDetail(orderDetailObj);
                    }
                    let productOrderDetailObj=data.data.productList;
                    if(!jQuery.isEmptyObject(productOrderDetailObj)){
                        productDetail(productOrderDetailObj.list);
                    }else{
                        productDetail([]);
                    }
                }
                tableList('returnMoneyTable','/bankFlow/query/returnMoney',returnColumns,returnParams);

                tableList('reviseRecordTable','/bankFlow/query/operatorLog',activeColumns,reviseParams);
            }
            else if(data.code == '-1'){
                $.alert(data.data)
            }
        }),
        error:(function() {
            $.alert('查询订单出错，请重试！');
        })
    })
}
/*全部关联、部分关联*/
function openReturnMoneyModal(type){
     returnMoneyBtn = arguments[1]?arguments[1]:'';
    if(type=='all'){
        relateType='D';
        $("#modalTitle").text("全部回款");
        $(".partRelationBtn").attr({"disabled":'disabled'});
        relationFile('all');//初始赋值
        $("#returnMoneyModal").modal("show");
        var bootstrapValidator = $("#returnMoneyForm").data('bootstrapValidator');
        if (bootstrapValidator) {
            $("#returnMoneyForm").data('bootstrapValidator').destroy();
            $('#returnMoneyForm').data('bootstrapValidator', null);
        }
        returnMoneyFormValidator();
    }else if(type=='part'){
        relateType='D';
        let parentsDom = $(returnMoneyBtn).parents('.productDetailModule');
        let money=$.trim(parentsDom.find('.partRelationMoney').val()).replaceAll(',','');
        let allMoney=$.trim(parentsDom.find('.residueMoney').text()).replaceAll(',','');
        if(money.length>0){
            if(Number(money)<=0){
                $.alert("关联金额大于0")
            }else{
                if(Number(allMoney)>=Number(money)){
                    submitRelation('part')
                }else{
                    $.alert("关联金额不能超过尾款")
                }
            }

        }else{
            $.alert("请填写关联金额")
        }

    }else if(type=='payNumber'){
        relateType='F';
        $("#modalTitle").text("充值回款");
        relationFile('payNumber');//初始赋值
        $("#returnMoneyModal").modal("show");
        var bootstrapValidator = $("#returnMoneyForm").data('bootstrapValidator');
        if (bootstrapValidator) {
            $("#returnMoneyForm").data('bootstrapValidator').destroy();
            $('#returnMoneyForm').data('bootstrapValidator', null);
        }
        returnMoneyFormValidator();

    }

}
$('#returnMoneyModal').on('hide.bs.modal', function () {
    $(".allRelationBtn").removeAttr('disabled');
    $(".partRelationBtn").removeAttr('disabled');
})
//提交关联
function submitRelation(type){
    // 验证表单
    if(type=='all'){
        var bootstrapValidator = $("#returnMoneyForm").data('bootstrapValidator');
        bootstrapValidator.validate();
        if (!bootstrapValidator.isValid()) {
            return;
        }
        $("#relateAllBtn").addClass("disabled");
    }else{
        $(returnMoneyBtn).addClass("disabled");
    }
    let parentsDom=$(returnMoneyBtn).parents('.productDetailModule');
    //提交关联参数
    let relationReturnMoneyParams= {
        'transactionDate': baseInfo.transactionDate,
        'creditMoney': baseInfo.creditMoney,
        'transactionNo': baseInfo.transactionNo,
        'arriveTime':baseInfo.transactionDate,
        'arriveMoney':type=='all'?Number($.trim($("#arriveMoney").val().replaceAll(',',''))):Number($.trim($(returnMoneyBtn).parents('.productFileContainer').find('.partRelationMoney').val()).replaceAll(',','')),
        'paymentUnit':type=='all'? $.trim($("#paymentUnit").val()):baseInfo.oppositeCompany,
        'paymentAccount':type=='all'?$.trim($("#paymentAccount").val()):(baseInfo.oppositeBankAccount?baseInfo.oppositeBankAccount:''),
        'paymentBank': type=='all'?$.trim($("#paymentBank").val()):(baseInfo.oppositeBank?baseInfo.oppositeBank:''),
        'arriveAccountType': type=='all'?$.trim($("#arriveAccountType").val()):baseInfo.payeeName,
        'remark': type=='all'?$.trim($("#remark").val()):'',
        'arriveType': type=='all'?0:1,
        'finishOrderProductId': type=='all'?'':parentsDom.find('.finishOrderProductId').text(),
        'finishOrderProductNum': type=='all'?'':parentsDom.find('.finishOrderProductNum').text(),
        'productOrderId': productOrderId,
        'orderNumber':$.trim($("#orderNumberText").text()),
        'productName':type=='all'?'':parentsDom.find('.productNameText').text(),
        'productCode':type=='all'?'':parentsDom.find('.productCode').text(),
        'orderDetailType':type=='all'?'':parentsDom.find('.orderDetailType').text(),
        'productCategories':type=='all'?'':parentsDom.find('.productCategories').text(),
        'productId':type=='all'?'':parentsDom.find('.productId').text(),
        'flowId':flowId,
        'payNumber':payNumber,
        'customerPayId':customerPayId,
        'customerId':customerId,
        'payType':payType,
        'relateType':relateType

    };
    $.ajax({
        url: '/bankFlow/relatedOrder',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(relationReturnMoneyParams),
        success:(function(data) {
            if(type=='part'){
                $(returnMoneyBtn).removeClass("disabled");
            }else{
                $("#relateAllBtn").removeClass("disabled");
            }
            if(data.code == '000000') {
                $.alert("关联成功")
                $("#returnMoneyModal").modal("hide");
                if(relateType=="D"){
                    updataResult();
                }else if(relateType=="F"){
                    //客户充值
                    tableList('customerPayTable','/customerPay/selectCustomerPayList',payNumberColumns,payNumberParams);
                    //回款
                    tableList('returnMoneyTable','/bankFlow/query/returnMoney',returnColumns,returnParams);
                    //修改
                    tableList('reviseRecordTable','/bankFlow/query/operatorLog',activeColumns,reviseParams);
                }
                assignment();
            }else if(data.code == '-1') {
                $.alert(data.data);
                $("#returnMoneyModal").modal("hide")
            }else if(data.code=='BFR0000'){
                $("#advancePayment").modal('show');
                $("#returnMoneyModal").modal("hide");
                if(relateType=="D"){
                    updataResult();
                }else if(relateType=="F"){
                    //客户充值
                    tableList('customerPayTable','/customerPay/selectCustomerPayList',payNumberColumns,payNumberParams);
                    //回款
                    tableList('returnMoneyTable','/bankFlow/query/returnMoney',returnColumns,returnParams);
                    //修改
                    tableList('reviseRecordTable','/bankFlow/query/operatorLog',activeColumns,reviseParams);
                }
                assignment();
            }else{
                $.alert(data.message);
                $("#returnMoneyModal").modal("hide")
            }
        }),
        error:(function() {
            if(type=='part'){
                $(returnMoneyBtn).removeClass("disabled");
            }else{
                $("#relateAllBtn").removeClass("disabled");
            }
            $.alert('请求错误');
        })
    })

}
/**
 * 功能：查看合作开发人员信息
 * */
function viewCooperate() {
    $.ajax({
        url: '/customerContract/selectContractCoDeveloperById',
        type: 'GET',
        dataType: 'json',
        data: {
            contractId: contractId
        },
        success: function (data) {
            if (data.code == '000000') {
                cooperateTable(data.data)
            } else {
                $.alert('获取开发人员信息出错，代码：' + data.code);
            }
        },
        error: function (err) {
            $.alert('获取开发人员信息失败！');
            console.log(err);
        }
    })
}
// 初始化合作开发人员信息列表
function cooperateTable(data) {
    $('#cooperateTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        data:data,
        striped: true,                      // 是否显示行间隔色
        undefinedText: '-',                 // cell没有值时显示
        pagination: true,                   // 是否显示分页
        pageSize: '5',                      // 每页的记录行数
        pageNumber: 1,                      // 初始化加载第1页，默认第1页
        pageList: ['5', '10'],              // 可供选择的每页的行数
        columns: [
            {title: '合作开发人员', field: 'userName', align: 'left', valign: 'middle'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '分配金额', field: 'allocationMount', align: 'left', valign: 'middle'},
        ]
    });
}
$('#cooperateModal').on('show.bs.modal', function () {
    viewCooperate();
})
//订单编号校验
function relationFormValidator(){
    $('#relationForm').bootstrapValidator({
        fields: {
            orderNumber: {
                validators: {
                    notEmpty: {
                        message: '订单编号不能为空'
                    }
                }
            }
        }
    })
}
//客户充值校验
function relationPayFormValidator(){
    $('#relationPayForm').bootstrapValidator({
        fields: {
            payNumber: {
                validators: {
                    notEmpty: {
                        message: '充值码不能为空'
                    }
                }
            }
        }
    })
}

//全部回款、部分回款弹出框字段校验
function returnMoneyFormValidator(){
    $('#returnMoneyForm').bootstrapValidator({
        fields: {
            arriveTime: {
                validators: {
                    notEmpty: {
                        message: '到款日期不能为空'
                    }
                }
            },
            arriveMoney: {
                validators: {
                    notEmpty: {
                        message: '到款金额不能为空'
                    }
                }
            },
            paymentUnit: {
                validators: {
                    notEmpty: {
                        message: '付款单位不能为空'
                    }
                }
            },
            arriveMethod: {
                validators: {
                    notEmpty: {
                        message: '到款方式不能为空'
                    }
                }
            },
            arriveAccountType: {
                validators: {
                    notEmpty: {
                        message: '到款账号类型不能为空'
                    }
                }
            }

        }
    })
}
$(document).on("show.bs.modal",'#returnMoneyModal',function(){
    $('body').removeClass("filter-blur");
    $(this).find('.modal-dialog').draggable();
})
//数值转换为会计数值格式
function toThousandsFormates(num) {
    // 判断传进来的数字是否为非空数字

    if (!isNaN(parseFloat(num))) {

        var newNum = Number(Number(num).toFixed(2)).toLocaleString('zh', { minimumFractionDigits: 0 })

        return newNum



    } else {

        return ''

    }

}

/*客户充值码查询*/
function searchPayNumber() {
    // 验证表单
    var bootstrapValidator = $("#relationPayForm").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }
    $("#orderNumber").val('');
    $("#orderNumberText").text('');
    productOrderId='';
    var bootstrapValidator = $("#relationForm").data('bootstrapValidator');
    if (bootstrapValidator) {
        $("#relationForm").data('bootstrapValidator').destroy();
        $('#relationForm').data('bootstrapValidator', null);
    }
    relationFormValidator();
    $("#payNumberText").text($("#payNumber").val())
    searchPayModuleShow();
    //客户充值
    tableList('customerPayTable','/customerPay/selectCustomerPayList',payNumberColumns,payNumberParams);
    //回款
    tableList('returnMoneyTable','/bankFlow/query/returnMoney',returnColumns,returnParams);
    //修改
    tableList('reviseRecordTable','/bankFlow/query/operatorLog',activeColumns,reviseParams);
}

function payTypeFormat(value, row, index) {
    var html = "";
    if (value == 1){
        html = "普通充值";
    }
    if (value == 2){
        html = "转入额";
    }
    return html;
}

function payStatusFormat(value, row, index) {
    var html = "";
    if (value == 0){
        html = "充值中";
    }
    if (value == 1){
        html = "已到账";
    }
    return html;
}

/*function alertContent(content){
    $("#tipText").text(content);
    $("#warningTip").hide();
    $("#advancePayment").modal('show');
}*/

